package com.wfl.sampling.service.impl;

import com.wfl.sampling.dao.GroupChatDao;
import com.wfl.sampling.entity.GroupChatDo;
import com.wfl.sampling.entity.GroupMessageDo;
import com.wfl.sampling.service.GroupChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class GroupChatServiceImpl implements GroupChatService {
    @Autowired
    private GroupChatDao groupChatDao;
    private final Lock createGroupChatLock = new ReentrantLock();

    public String createGroupChat(GroupChatDo groupChatDo) {
        try {
            createGroupChatLock.lock();
            // 获取ID和创建群聊过程是同步的
            Integer groupChatId = groupChatDao.selectCurrentAutoId();
            groupChatDo.setGroupChatId(groupChatId+1);
            groupChatDao.createGroupChat(groupChatDo);
            groupChatDao.createGroupChatWithMember(groupChatDo);

        } finally {
            createGroupChatLock.unlock(); // 确保锁在方法结束时释放
        }

        return "创建成功";
    }

    @Override
    public ArrayList<GroupMessageDo> getGroupMessage(Integer groupId) {
        return groupChatDao.selectGroupMessage(groupId);
    }

    @Override
    public String saveConversionMessage(Integer userId, Integer groupId, String message) {
         groupChatDao.saveConversionMessage(userId,groupId,message);
         return "保存成功";
    }
}
